package urlparse

import (
	"errors"
	"strings"
)

type Parse struct {
	PreFix   string `json:"pre_fix"`   // 前缀
	Address  string `json:"address"`   // 地址
	UserName string `json:"user_name"` // 登录名
	PassWord string `json:"pass_word"` // 登录密钥

	Kwargs map[string]string `json:"kwargs"` // 链接参数
}

func (p *Parse) SetParseUrl(url string) error {
	pf := strings.Index(url, "://")
	if pf < 0 {
		return errors.New("url prefix not exists")
	}
	p.PreFix = url[:pf]
	up := strings.Index(url, "@")
	if up < 0 {
		return errors.New("username and password not exists")
	}
	if up != pf+3 {
		u2p := strings.Split(url[pf+3:up], ":")
		p.UserName, p.PassWord = u2p[0], u2p[1]
	}
	ad := strings.Index(url[up+1:], "?")
	if ad < 0 {
		if url[up+1:][len(url[up+1:])-1] == '/' {
			p.Address = url[up+1 : len(url[up+1:])-1]
		} else {
			p.Address = url[up+1:]
		}
	} else {
		addr := url[up+1:][:ad]
		if addr[len(addr)-1] == '/' {
			p.Address = addr[:len(addr)-1]
		} else {
			p.Address = addr
		}
		p.Kwargs = map[string]string{}
		for _, ele := range strings.Split(url[up+1:][ad+1:], "&") {
			kv := strings.Split(ele, "=")
			p.Kwargs[kv[0]] = kv[1]
		}
	}
	return nil
}
